package cn.tedu.ivos.user.service.impl;

import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.base.response.StatusCode;
import cn.tedu.ivos.base.util.PasswordUtil;
import cn.tedu.ivos.user.mapper.UserMapper;
import cn.tedu.ivos.user.pojo.dto.UserLoginParam;
import cn.tedu.ivos.user.pojo.dto.UserQuery;
import cn.tedu.ivos.user.pojo.dto.UserSaveParam;
import cn.tedu.ivos.user.pojo.entity.User;
import cn.tedu.ivos.user.pojo.vo.UserVO;
import cn.tedu.ivos.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public UserVO login(UserLoginParam userLoginParam) {
        log.debug("开始处理用户登录的请求..." + userLoginParam);
        UserVO userVO = userMapper.selectByUsername(userLoginParam.getUsername());
        if (userVO == null) {
            throw new ServiceException(StatusCode.USERNAME_ERROR);
        }
        if (!userVO.getPassword().equals(userLoginParam.getPassword())) {
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }
        log.debug("用户登录成功，用户信息：" + userVO);
        return userVO;
    }

    @Override
    public List<UserVO> selectUser(UserQuery userQuery) {
        log.debug("开始处理查询用户请求..." + userQuery);
        List<UserVO> list = userMapper.selectUser(userQuery);
        return list;
    }

    @Override
    public void saveUser(UserSaveParam userSaveParam) {
        log.debug("开始处理保存用户请求..." + userSaveParam);
        User user = new User();
        BeanUtils.copyProperties(userSaveParam, user);
        if (user.getId() == null) {
            user.setPassword("123456");
            user.setCreateTime(new Date());
            userMapper.insertUser(user);
        } else {
            user.setUpdateTime(new Date());
            userMapper.updateUser(user);
        }
    }

    @Override
    public void resetPassword(Long userId) {
        log.debug("开始处理重置密码请求..." + userId);
        User user = new User();
        user.setId(userId);
//        user.setPassword("654321");
        user.setPassword(PasswordUtil.generatePassword(8));
        log.debug("重置密码成功，新密码：" + user.getPassword());
        user.setUpdateTime(new Date());
        userMapper.updateUser(user);

    }

    @Override
    public void resetStatus(Long userId, String status) {
        log.debug("开始处理重置状态请求..." + userId + " " + status);
        User user = new User();
        user.setId(userId);
        user.setStatus(status);
        user.setUpdateTime(new Date());
        userMapper.updateUser(user);
    }

    @Override
    public void deleteUser(Long userId) {
        log.debug("开始处理删除用户请求..." + userId);
        userMapper.deleteUser(userId);
    }
}





























